<template>
  <a-card :bordered="false">
    <div class="title-wrap">
      <div class="title">项目分类</div>
      <a-button
        type="primary"
        @click="addNewRow"
        class="title-button"
      >新增分类</a-button>
    </div>
    <a-row class="content-wrap">
      <a-col :span="8">
        <a-spin v-if="loading" />
        <template v-else>
          <a-tree
            :load-data="onLoadData"
            :tree-data="treeData"
            :replaceFields="treeFields"
            @select="setSelectRow"
          />
        </template>
      </a-col>
      <a-col
        :span="16"
        style="border-left: solid 1px #E9E9E9;"
      >
        <a-form
          :form="form"
          @submit="handleSubmit"
        >
          <a-form-item
            label="分类名称"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
          >
            <a-input
              v-decorator="[
                'categoryName',
                {rules: [{ required: true, message: '请输入分类名称' }]}
              ]"
              name="categoryName"
              placeholder="分类名称"
            />
            <a-input
              v-decorator="[
                'categoryId'
              ]"
              hidden
            />
          </a-form-item>
          <a-form-item
            label="分类图片"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
          >
            <a-upload
              name="imageUrl"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUploadImage"
            >
              <img
                v-if="form.getFieldValue('imageUrl')"
                :src="imageUrlPrefix + form.getFieldValue('imageUrl')"
                alt="imageUrl"
                style="max-width: 100%;"
              />
              <div v-else>
                <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  {{ uploadLoading ? '上传中' : '上传' }}
                </div>
              </div>
            </a-upload>
            <a-input
              hidden
              v-decorator="[
                'imageUrl',
                {rules: [{ required: true, message: '请上传分类图片' }]}
              ]"
            />
          </a-form-item>
          <a-form-item
            label="分类图标"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
          >
            <a-upload
              name="iconUrl"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUploadIcon"
            >
              <img
                v-if="form.getFieldValue('icon')"
                :src="imageUrlPrefix + form.getFieldValue('icon')"
                alt="iconUrl"
                style="max-width: 100%;"
              />
              <div v-else>
                <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  {{ uploadLoading ? '上传中' : '上传' }}
                </div>
              </div>
            </a-upload>
            <a-input
              hidden
              v-decorator="[
                'icon',
              ]"
            />
          </a-form-item>
          <a-form-item
            label="父级分类"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
          >
            <a-select
              v-decorator="[
                'parentId',
                {rules: [{ required: true, message: '请选择父级分类' }]}
              ]"
              style="width: 100%"
              placeholder="请选择父级分类"
              allowClear
            >
              <a-select-option :value="0">【根】</a-select-option>
              <a-select-option
                v-for="el in treeData"
                :key="el.categoryId"
                :value="el.categoryId"
              >{{ el.categoryName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="小程序首页展示"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
          >
            <a-switch
              checked-children="是"
              un-checked-children="否"
              v-decorator="[
                'isHot', {
                  valuePropName: 'checked',
                  initialValue: false
                }
              ]"
            />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 10, offset: 4 }">
            <a-popconfirm
              title="是否要删除此分类？"
              @confirm="deleteRow"
            >
              <a-button
                type="info"
                v-show="selectedId"
                :loading="submitLoading"
                style="margin-right: 12px;"
              >删除</a-button>
            </a-popconfirm>
            <a-button
              type="primary"
              html-type="submit"
              :loading="submitLoading"
            >
              确定
            </a-button>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import { getCategoryChild, addCategoryChild, deleteCategory, updateCategoryChild, uploadImage } from '@/api/manage'
import config from '@/config/defaultSettings'

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  data() {
    return {
      treeData: [],
      treeFields: {
        children: 'children',
        title: 'categoryName',
        key: 'categoryId'
      },
      loading: false,
      selectedId: null,
      form: this.$form.createForm(this),
      submitLoading: false,
      uploadLoading: false,
      file: null,
      imageUrlPrefix: config.uploadedUrlPrefix
    }
  },
  created() {
    this.getRootData()
  },
  methods: {
    getRootData() {
      this.loading = true
      this.getChild(0).then(res => {
        this.treeData = res
      }).finally(() => {
        this.loading = false
      })
    },
    getChild(parentId) {
      return new Promise(resolve => getCategoryChild(parentId).then(res => {
        if (res.resData) {
          const data = res.resData.map(el => Object.assign({ scopedSlots: { title: 'custom' } }, el))
          resolve(data)
        } else {
          this.$notification.warning({
            message: '数据出错'
          })
        }
      }))
    },
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        this.getChild(treeNode.dataRef.categoryId).then(children => {
          treeNode.dataRef.children = children.map(el =>
            Object.assign({
              scopedSlots: { title: 'custom' },
              isLeaf: true
            }, el))
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.doSubmit(values)
        }
      })
    },
    doSubmit(values) {
      this.submitLoading = true
      const postMethods = values.categoryId ? updateCategoryChild : addCategoryChild
      postMethods(values).then(res => {
        this.$message.success('新增成功')
        this.treeData = []
        this.getRootData()
        this.addNewRow()
      }).catch(err => {
        console.log(err)
        this.$message.error(`新增失败`)
      }).finally(() => {
        this.submitLoading = false
      })
    },
    setSelectRow(selectedKeys, { selected: bool, selectedNodes, node, event }) {
      this.selectedId = node.dataRef.categoryId
      this.form.setFieldsValue({
        categoryId: node.dataRef.categoryId,
        categoryName: node.dataRef.categoryName,
        icon: node.dataRef.icon,
        imageUrl: node.dataRef.imageUrl,
        isHot: node.dataRef.isHot,
        parentId: node.dataRef.parentId
      })
    },
    deleteRow() {
      this.submitLoading = true
      deleteCategory(this.selectedId).then(res => {
        this.getRootData()
        this.addNewRow()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.error(`删除失败`)
      }).finally(() => {
        this.submitLoading = false
      })
    },
    addNewRow() {
      this.selectedId = null
      this.form.resetFields()
    },
    handleChangeIcon(info) {
      if (info.file.status === 'uploading') {
        this.iconLoading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.form.setFieldsValue({
            icon: imageUrl
          })
          this.iconLoading = false
        })
      }
    },
    beforeUploadImage(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      this.file = file
      if (!isJpgOrPng) {
        this.$message.error('只能上传JPG或PNG图片！')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片需小于10M')
      }
      if (isJpgOrPng && isLt2M) {
        this.handleFileUpload('imageUrl')
      }
      return false
    },
    beforeUploadIcon(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      this.file = file
      if (!isJpgOrPng) {
        this.$message.error('只能上传JPG或PNG图片！')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片需小于10M')
      }
      if (isJpgOrPng && isLt2M) {
        this.handleFileUpload('icon')
      }
      return false
    },
    handleFileUpload(fieldName) {
      const formData = new FormData()
      formData.append('imageFile', this.file)
      this.uploadLoading = true
      uploadImage(formData).then(res => {
        this.form.setFieldsValue({
          [fieldName]: res.resData && res.resData.result
        })
      }).catch(() => {
        this.file = null
        this.$message.error('上传失败，请重试')
      }).finally(() => {
        this.uploadLoading = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.title-wrap {
  display: flex;
  justify-content: space-between;
  margin-top: -24px;
  height: 54px;
  line-height: 54px;
  border-bottom: solid 1px #e9e9e9;
  .title {
    font-size: 18px;
    color: #333;
    font-weight: 500;
  }
  .title-button {
    margin-top: 12px;
  }
}
.content-wrap {
  padding: 24px;
}
</style>
